package com.lkj.controller;

import cn.hutool.core.io.FileUtil;
import com.lkj.common.Constant;
import com.lkj.config.FileConfig;
import com.lkj.utils.FileUploadUtils;
import com.lkj.utils.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author likanjie
 * @Date 2020/9/7 9:25 下午
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("/download")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String downloadPath = "/Users/likanjie/Documents/Java/gather/file-upload-download/uploadPath/upload/2020/09/07/1599488936178.png";

        String downloadName = "1599488936178.png";

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-date");
        response.setHeader("Content-Disposition","attachment;fileName="+FileUtils.setFileDownloadHeader(request,downloadName));

        FileUtils.writeBytes(downloadPath,response.getOutputStream());
    }


    @PostMapping("/uploadFile")
    public String upload(MultipartFile file) {

        String uploadPath = FileConfig.getUploadPath();

        try {
            String upload = FileUploadUtils.upload(uploadPath, file);
            return upload;
        } catch (IOException e) {

            e.printStackTrace();
        }

        return "";
    }
}
